package com.jung.images.action;

import com.jung.images.model.Images;
import com.jung.images.service.ImagesService;
import com.opensymphony.xwork2.ActionSupport;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import javax.annotation.Resource;
import javax.servlet.ServletContext;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.util.ServletContextAware;

public class ImagesAction extends ActionSupport implements ServletContextAware {

	private static final long serialVersionUID = 3952930119422819339L;
	private File doc;
	private Images images;
	private ServletContext context;
	private ImagesService imagesService;

	@Resource
	public void setImagesService(ImagesService imagesService) {
		this.imagesService = imagesService;
	}

	public void setDoc(File file) {
		this.doc = file;
	}

	public void setServletContext(ServletContext context) {
		this.context = context;
	}

	public String upload() throws Exception {
		String targetDirectory = context.getRealPath("/upload");
		String targetFileName = generateFileName(images.getFileName());
		File target = new File(targetDirectory, targetFileName);
		FileUtils.copyFile(doc, target);
		return SUCCESS;
	}

	private String generateFileName(String fileName) {

		DateFormat format = new SimpleDateFormat("yyMMddHHmmss");
		String formatDate = format.format(new Date());
		int random = new Random().nextInt(10000);
		int position = fileName.lastIndexOf(".");
		String extension = fileName.substring(position);
		return formatDate + random + extension;

	}

	public String delete() {
		return SUCCESS;
	}

	public String update() {
		return SUCCESS;
	}
}
